package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 员工管理模块
 */
@Slf4j
@RestController
@RequestMapping("employee")
@Api(tags = "员工管理模块")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     */
    @ApiOperation("登录")
    @PostMapping("login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        //1. 根据用户名查询 select * from employee where username=?
        /*LambdaQueryWrapper<Employee> wrapper = Wrappers.lambdaQuery(Employee.class)
                .eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wrapper);*/

        Employee one = employeeService.lambdaQuery()
                .eq(Employee::getUsername, employee.getUsername())
                .one();

        if (one == null) {
            //说明账号不存在
            return R.error("账号不存在");
        }

        //2. 判断密码是否正确（employee的密码 == one的密码）
        String password = employee.getPassword();
        //对password进行md5加密
        String md5 = DigestUtils.md5Hex(password);
        if (!StringUtils.equals(md5, one.getPassword())) {
            //说明密码错误
            return R.error("密码错误");
        }

        //3. 判断账号的状态（one的状态）
        if (one.getStatus() == 0) {
            //说明账号已被禁用
            return R.error("账号已被禁用");
        }

        //4. 说明登录成功（将员工id存入session中）
        session.setAttribute("employee", one.getId());
        return R.success(one);
    }


    /**
     * 员工退出
     */
    @PostMapping("logout")
    public R<String> logout(HttpSession session) {
        //1. 销毁session对象
        session.invalidate();
        //2. 返回code=1
        return R.success("退出成功");
    }


    /**
     * 添加员工
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        //1. 由于employee对象中缺少部分数据，进行数据补全（password,时间...）
        employee.setPassword(DigestUtils.md5Hex("123456")); //设置密码
        //2. 调用service保存数据
        employeeService.save(employee);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @GetMapping("page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "员工名称"),
            @ApiImplicitParam(name = "page", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数")
    })
    public R<Page<Employee>> page(String name, Integer page, Integer pageSize) {
        //select * from employee where name like ? limit ?, ?

        //1. 创建分页对象信息Page
        Page<Employee> pageInfo = new Page<>(page, pageSize);

        //2. 调用业务层
        employeeService.lambdaQuery()
                .like(StringUtils.isNotBlank(name), Employee::getName, name) //条件
                .orderByDesc(Employee::getCreateTime) //根据添加时间降序
                .orderByDesc(Employee::getUpdateTime) //根据修改时间降序
                .page(pageInfo);

        //3. 返回数据
        return R.success(pageInfo);
    }

    /**
     * 启用、禁用员工状态
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        // update employee set status=? where id=?
        // updateById：employee对象中属性有值的就会更新
        employeeService.updateById(employee);
        return R.success("修改成功");
    }


    /**
     * 根据id查询
     */
    @GetMapping("{id}")
    public R<Employee> findById(@PathVariable Long id) {
        //调用业务层
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }

}




